﻿using RQX.Common.Core.Extension;
using RQX.Common.Core.Hardware.BaseCollection;
using RQX.Common.Core.Hardware.Com;
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Drager_Primus
{
    public class Primus : AbstractComCollection
    {
        #region 初始属性

        public override DeviceType DeviceType => DeviceType.麻醉机;
        public override int BaudRate => 9600;

        public override int DataBits => 8;

        public override StopBits StopBits => StopBits.One;

        public override Parity Parity => Parity.Even;

        public override bool DTR => false;

        public override bool RTS => false;
        #endregion
        private bool IsCircleSend = false;

        public Primus() { }
        public Primus(StructureModel<MyCom> model) : base(model)
        {
        }
        /// <summary>
        /// 解析
        /// </summary>
        /// <param name="buffer"></param>
        /// <returns></returns>
        protected override Dictionary<string, string> AnalysisData(string msg)
        {
            var buffer = msg.HexStringToByte();
            Dictionary<string, string> dic_result = new Dictionary<string, string>();
            if (buffer.Length > 5 && buffer[0] == 0x01 && buffer[1] == 0x24)
            {
                for (var i = 2; i < buffer.Length - 9; i += 6)
                {
                    string code = $"{Convert.ToChar(buffer[i])}{Convert.ToChar(buffer[i + 1])}";
                    var value = $"{buffer[i + 2].ToChar()}{buffer[i + 3].ToChar()}{buffer[i + 4].ToChar()}{buffer[i + 5].ToChar()}";
                    if (dic.ContainsKey(code))
                    {
                        if (!dic_result.ContainsKey(dic[code]))
                        {
                            dic_result.Add(dic[code], value.Trim());
                        }
                        else
                        {
                            dic_result[dic[code]] = value.Trim();
                        }
                    }
                }
            }
            return dic_result;
        }

        protected override StepType CheckRecvMsgType(string lineStr)
        {
            switch (lineStr)
            {
                case "1b5136430d":return StepType.Init;
                case "1b5236440d":return StepType.Setp1;
            }
            if (lineStr.StartsWith("0124")) return StepType.DataSource;
            return StepType.None;
            //if (lineStr.IsNullOrEmpty()) return StepType.None;
            //var ds = lineStr.HexStringToByte();
            //if (ds.Length>5 && ds[0] == 0x01 && ds[1] == 0x24)
            //{
            //    return StepType.DataSource;
            //}
            //return StepType.None;
        }
        protected override void CircleSend()
        {
            if(IsCircleSend == false)
            {
                IsCircleSend = true;
                Task.Run(() =>
                {
                    while (IsCircleSend)
                    {
                        Thread.Sleep(2000);
                        Send(request_current_data.HexStringToByte());//请求当前数据
                    }
                });
            }
        }

        protected override void Connect(StepType type, string msg = "")
        {
            switch (type)
            {
                case StepType.Init:
                    IsCircleSend = false;
                    Send(response_icc.HexStringToByte());//icc 响应
                    break;
                case StepType.Setp1:
                    Thread.Sleep(500);
                    Send(request_deviceId_cmd.HexStringToByte());//请求设备ID
                    Task.Run(() =>
                    {
                        Thread.Sleep(1000);
                        Send(response_deviceId_empty.HexStringToByte());//回应麻醉机的设备ID获取，empty Device Identification
                        CircleSend();
                    });
                    break;
            }
            //if (type == StepType.Init)
            //{
            //    Task.Run(() =>
            //    {
            //        Thread.Sleep(2000);
            //        Send(response_icc.HexStringToByte());//icc 响应
            //        Thread.Sleep(1000);
            //        Send(request_deviceId_cmd.HexStringToByte());//请求设备ID
            //        Thread.Sleep(1000);
            //        Send(response_deviceId_empty.HexStringToByte());//回应麻醉机的设备ID获取，empty Device Identification
            //        CircleSend();
            //    });
            //}
        }

        protected override string CutToOneMsg(StringBuilder sb)
        {
            if (sb.Length < 5) return "";
            var msg = "";
            var index = sb.ToString().IndexOf("0d");
            if (index > -1)
            {
                msg = sb.ToString().Substring(0, index + 2);
                WriteDebugLogMethod(msg);
            }
            return msg;
        }

        #region 内部数据
        private const string response_icc = "01 51 35 32 0d";//icc 响应
        private const string request_deviceId_cmd = "1b 52 36 44 0d";//请求设备ID
        private const string response_deviceId_empty = "01 52 35 33 0d";//回应麻醉机的设备ID获取，empty Device Identification
        private const string request_current_data = "1b 24 33 46 0d";//请求当前数据

        private static Dictionary<string, string> dic = new Dictionary<string, string>()
        {
            {"1B","Consumption Halothane (Liquid)"},
            {"1C","Consumption Enflurane (Liquid)"},
            {"1D","Consumption Isoflurane (Liquid)"},
            {"1E","Consumption Desflurane (Liquid)"},
            {"1F","Consumption Sevoflurane (Liquid)"},
            {"50","Insp.Halothane"},
            {"51","Exp.Halothane"},
            {"52","Insp.Enflurane"},
            {"53","Exp.Enflurane"},
            {"54","Insp.Isoflurane"},
            {"55","Exp.Isoflurane"},
            {"56","Insp.Desflurane"},
            {"57","Exp.Desflurane"},
            {"58","Insp.Sevoflurane"},
            {"59","Exp.Sevoflurane"},
            {"5A","Insp.Agent"},
            {"5B","Exp.Agent"},
            {"5C","2nd Insp.Agent"},
            {"5D","2nd Exp.Agent"},
            {"AC","Insp.MAC"},
            {"AD","Exp.MAC"},
            {"AE","Insp.Desflurane"},
            {"AF","Exp.Desflurane"},
            {"B0","Insp.Sevoflurane"},
            {"B1","Exp.Sevoflurane"},
            {"E9","Insp.Agent"},
            {"EA","Exp.Agent"},
            {"ED","Insp.2nd Agent"},
            {"EE","Exp.2nd Agent"},
            {"F4","Insp.Halothane"},
            {"F5","Exp.Halothane"},
            {"F6","Insp.Enflurane"},
            {"F7","Exp.Enflurane"},
            {"F8","Insp.Isoflurane"},
            {"F9","Exp.Isoflurane"},
            {"FB","Insp.N2O"},
            {"FC","Exp.N2O"},
            {"05","Breathing Pressure"},
            {"06","Compliance"},
            {"6B","Ambient pressure"},
            {"73","Mean Breathing Pressure"},
            {"74","Plateau Pressure"},
            {"78","PEEP Breathing Pressure"},
            {"7D","Peak Breathing Pressure"},
            {"88","Tidal Volume"},
            {"8B","Insp.Tidal Volume"},
            {"B4","Respiratory Rate (Pressure)"},
            {"B9","Respiratory Minute Volume"},
            {"BD","Apnea Duration"},
            {"D7","Respiratory Rate (Volume/Flow)"},
            {"D9","Respiratory Rate (derived)"},
            {"D5","Respiratory Rate (CO2)"},
            {"DA","Insp.CO2 in %"},
            {"DB","Endtidal CO2 in %"},
            {"E3","Endtidal CO2 in kPa"},
            {"E5","Insp.CO2 mmHg"},
            {"E6","Endtidal CO2 in mmHg"},
            {"FF","Insp.CO2 kPa"},
            {"C4","Delta O2 (Insp.O2 - Exp.O2)"},
            {"EF","Exp.O2"},// 呼出氧气率
            {"F0","Insp.O2"},//吸入氧气率
            {"64","O2 Uptake"},
            {"E1","Pulse Rate (OXIMETER)"},
            {"EB","Oxygen Saturation"},
            {"DF","Pulse Rate (derived)"},
            {"B2","Leakage mL/min"},
            {"DD","N2O Flow"},
            {"DE","Air Flow"},
            {"E2","O2 Flow ml/min"},//氧气流量
        };

        #endregion
    }
}
